from io import BytesIO
from lxml import etree
from PIL import Image
from sys import version_info
import base64
import requests
import json


def base64_api(uname, pwd, img):
    img = img.convert('RGB')
    buffered = BytesIO()
    img.save(buffered, format="JPEG")
    if version_info.major >= 3:
        b64 = str(base64.b64encode(buffered.getvalue()), encoding='utf-8')
    else:
        b64 = str(base64.b64encode(buffered.getvalue()))
    data = {"username": uname, "password": pwd, "image": b64, 'typeid': '7'}
    result = json.loads(requests.post("http://api.ttshitu.com/base64", json=data).text)
    if result['success']:
        return result["data"]["result"]
    else:
        return result["message"]
    return ""


login_url = "https://www.v2ex.com/signin"

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36',
    'cookie': '__cfduid=dd420483f64b5c175f6109b6b8b8b97ae1592959698; PB3_SESSION="2|1:0|10:1593527523|11:PB3_SESSION|40:djJleDoxNzIuMTA1LjExOC4yMTA6MzQ3OTYwMjU=|593f4eb574c36f9195bba7f738cd85e5a4bd7dceb98f0b9ca365f1221d2e1b4b"; V2EX_LANG=zhcn; __gads=ID=d8d8486d48cbdbb9:T=1593527524:S=ALNI_MYNrzxLtNfYpMBDMbjTKjTBZG02yw; _ga=GA1.2.amp-E0RuTNsc0X_BnpkPjc4xmw; _gid=GA1.2.1224388420.1593527525; cf_chl_1=2b31629f19fbb7e; cf_clearance=7c245722bfe45cb86914744384176c62eb5527df-1593529058-0-1z9ef983dazb8385daz54e081bd-150'
}

# 获取参数
session = requests.Session()
login_res = session.get(login_url, headers=headers)
html = etree.HTML(login_res.text)
inputs = html.xpath("//form[@action='/signin']//input")
user_input = inputs[0].get('name')
password_input = inputs[1].get('name')
capt_input = inputs[2].get('name')
once_input = inputs[3].get('value')

# 获取验证码
new_url = f"https://www.v2ex.com/_captcha?once={once_input}"
response = session.get(new_url, headers=headers)
with open('captcha.png', 'wb') as f:
    f.write(response.content)

# 解密验证码
img_path = r"captcha.png"
img = Image.open(img_path)
result = base64_api(uname='luckyy', pwd='199213xiao', img=img)
print(result)

data = {
    user_input: 'hyever',
    password_input: 'abcabc',
    capt_input: result,
    'once': once_input,
    'next': '/'
}
print(data)
headers['referer'] = "https://www.v2ex.com/signin"
res = session.post(login_url, data=data, headers=headers)
print(res.text)
